<?php
/**
 * Created by PhpStorm.
 * User: Keter
 * Date: 2016/8/17
 * Time: 16:52
 */
class ShareConfigInfo extends DatabaseBase
{
    public function updateNotify()
    {
        $result = false;

        try {
            $config = $this->get();
            $result = $this->writeConfig($config);
        } catch (Exception $e) {
            $this->e('消息配置更新失败');
            return false;
        }

        return $result;
    }

    /**
     * 获取配置（外部统一使用函数）
     * 以后有后台控制，可以改用getConfigByRedis()
     * @return $name
     */
    public function get($name = null)
    {
        $config = $this->getConfigByRedis();

        if (func_num_args()) {
            if (isset($config[$name])) {
                return $config[$name];
            }
            return null;
        }

        return $config;
    }

    /**
     * 从Redis中获取
     * @return array
     */
    public function getConfigByRedis()
    {
        //系统广播
        $sysMsgKeys  = $this->redis->keys('SC:*');
        $fields = array('id', 'name', 'value');
        $config = array();

        foreach ($sysMsgKeys as $value) {
            $row = $this->redis->hMget($value, $fields);
            if ($row) {
                $config[$row['name']] = $row['value'];
            }
        }

        return $config;
    }

    /**
     * 写配置
     * @param $config
     */
    public function writeConfig($config)
    {
        $dir = pathFormat('data/contents/');
        if ($error = $this->checkDir($dir)) {
            $this->e($error);
        }

        //写配置内容
        $config['timestamp'] = time();
        $configFile = $dir . 'config.txt';
        $configContent = json_encode($config, JSON_UNESCAPED_UNICODE);
        $ret = $this->writeFile($configFile, $configContent);

        //更新时间戳
        if ($ret) {
            $updateFile = $dir. 'update.txt';
            $content = json_encode(array('timestamp' => $config['timestamp']));
            $ret = $this->writeFile($updateFile, $content);
            if (!$ret) {
                return false;
            }
        }

        return true;
    }
}